package com.itheima.admin.filter;
import cn.hutool.jwt.JWT;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Locale;

/**
 * @author :WuJunJie
 * packageName :com.itheima.admin.filter
 * fileName :loginFilter
 * creationTime :2022-11-06 14:48
 */
@WebFilter("/*")
@Slf4j
//@Component
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest hsr= (HttpServletRequest) servletRequest;
        String requestURI = hsr.getRequestURI();
        Boolean flag = (Boolean) hsr.getAttribute("flag");
        if (flag){
            log.info("已被放行");
            filterChain.doFilter(servletRequest,servletResponse);
        }

        if ("/admin/login".equals(requestURI)){
            log.info("登录放行");
            filterChain.doFilter(servletRequest,servletResponse);
        }

        if ("get".equals(hsr.getMethod().toLowerCase(Locale.ROOT))){
            log.info("get请求放行");
            filterChain.doFilter(servletRequest,servletResponse);
        }


            BufferedReader br = new BufferedReader(new InputStreamReader(hsr.getInputStream()));
            String line;
            StringBuilder sb=new StringBuilder();
            while ((line=br.readLine())!=null){
                sb.append(line);
            }
        log.info("前端请求的数据：{}",sb);
            HashMap<String,String> hm = JSON.parseObject(sb.toString(), HashMap.class);


            if(hm!=null) {
                String token = hm.get("token");
                boolean verify = JWT.of(token).setKey("336699".getBytes()).verify();
                if (verify) {
                    log.info("token正确，放行");
                    filterChain.doFilter(servletRequest, servletResponse);
                }
            }


    }
}
